package com.techsoul.module.pms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.exception.BusinessException;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelExport;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.common.security.util.SecurityUtils;
import com.techsoul.module.accounting.mapper.AccountingArMapper;
import com.techsoul.module.accounting.pojo.entity.AccountingAr;
import com.techsoul.module.accounting.pojo.vo.AccountingArVo;
import com.techsoul.module.basic.mapper.*;
import com.techsoul.module.basic.pojo.entity.*;
import com.techsoul.module.basic.pojo.vo.CustomerConsigneeDeliveryAddressVo;
import com.techsoul.module.basic.pojo.vo.WarehouseVo;
import com.techsoul.module.goods.pojo.entity.Sku;
import com.techsoul.module.pms.enmus.InAndOutTypeEnum;
import com.techsoul.module.pms.enmus.WmsInStatusEnum;
import com.techsoul.module.pms.mapper.*;
import com.techsoul.module.pms.pojo.entity.*;
import com.techsoul.module.pms.pojo.param.*;
import com.techsoul.module.pms.pojo.vo.*;
import com.techsoul.module.pms.service.IBmsAllGeneralSeqTabService;
import com.techsoul.module.pms.service.ITbWmsMaterialDeliveryLineService;
import com.techsoul.module.pms.service.ITbWmsMaterialDeliveryService;
import com.techsoul.module.system.pojo.param.UserSaveParam;
import com.techsoul.module.system.service.IConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 出库单 Service实现
 *
 * @author liuen
 * @date 2022-01-25
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class TbWmsMaterialDeliveryServiceImpl implements ITbWmsMaterialDeliveryService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TbWmsMaterialDeliveryMapper mapper;
    @Autowired
    private MyCalendarMapper myCalendarMapper;
    @Autowired
    private IBmsAllGeneralSeqTabService tBmsAllGeneralSeqTabService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TbWmsTemplateMapper tbWmsTemplateMapper;
    @Autowired
    private TbWmsTemplateLineMapper tbWmsTemplateLineMapper;
    @Autowired
    private TbWmsMaterialReceiptLineMapper tbWmsMaterialReceiptLineMapper;
    @Autowired
    private TbWmsMaterialReceiptMapper tbWmsMaterialReceiptMapper;

    @Autowired
    private TbWmsMaterialDeliveryLineMapper tbWmsMaterialDeliveryLineMapper;
    @Autowired
    private IConfigService configService;
    @Autowired
    private CustomerConsigneeMapper customerConsigneeMapper;
    @Autowired
    private CustomerConsigneeDeliveryAddressMapper customerConsigneeDeliveryAddressMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private TbUserWarehouseManagerMapMapper tbUserWarehouseManagerMapMapper;

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private AccountingArMapper accountingArMapper;

    @Autowired
    private TbWmsMaterialInLocationMapper tbWmsMaterialInLocationMapper;
    @Autowired
    private ITbWmsMaterialDeliveryLineService materialDeliveryLineService;

    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(TbWmsMaterialDeliverySaveParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        TbWmsMaterialDelivery entity = new TbWmsMaterialDelivery();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(TbWmsMaterialDeliverySaveParam params) {
        TbWmsMaterialDelivery entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(sysUser.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public TbWmsMaterialDeliveryVo findById(String id) {
        return this.mapper.findById(id);
    }
    @Override
    public TbWmsMaterialDeliveryVo getOrderDetail(String id) {
        TbWmsMaterialDeliveryVo tbWmsMaterialDeliveryVo= this.mapper.findById(id);
        List<TbWmsMaterialInLocationVo> tbWmsMaterialInLocationVos =
                new ArrayList<TbWmsMaterialInLocationVo>();
        List<AccountingArVo> accountingArVos=
        new ArrayList<AccountingArVo>();
        accountingArVos=this.accountingArMapper.findBYDeliveryLineId(tbWmsMaterialDeliveryVo.getId());
        List<TbWmsMaterialDeliveryLineVo> items =tbWmsMaterialDeliveryVo.getReceitems();
        for(int i = 0;i<items.size();i++){
            TbWmsMaterialDeliveryLineVo thisitem = (TbWmsMaterialDeliveryLineVo)items.get(i);
            if(thisitem.getReceivedLineId()!=null){
                List<AccountingArVo> recears = this.accountingArMapper.findBYReceLineId(thisitem.getReceivedLineId());
                accountingArVos.addAll(recears);
                List<TbWmsMaterialInLocationVo> thisInLocationVos
                        =this.tbWmsMaterialInLocationMapper.findVoByReciptLineId(thisitem.getReceivedLineId());
                tbWmsMaterialInLocationVos.addAll(thisInLocationVos);
            }else{
                List<TbWmsMaterialInLocationVo> thisInLocationVos
                        =this.tbWmsMaterialInLocationMapper.findVoByMaterialNo(thisitem.getMaterialNo());
                tbWmsMaterialInLocationVos.addAll(thisInLocationVos);
            }
        }

        tbWmsMaterialDeliveryVo.setLineArs(accountingArVos);
        tbWmsMaterialDeliveryVo.setLocationItems(tbWmsMaterialInLocationVos);
        return tbWmsMaterialDeliveryVo;
    }

    /**
     * 详情-根据单号查询
     * @param orderNo
     * @return
     */
    @Override
    public TbWmsMaterialDeliveryVo findByOrderNo(String orderNo) {
        return this.mapper.findByOrderNo(orderNo);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<TbWmsMaterialDeliveryVo> findAll(TbWmsMaterialDeliverySearchParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<TbWmsMaterialDeliveryVo> findAll(TbWmsMaterialDeliverySearchParam params, Integer current, Integer pageSize) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
      //
        //  params.setSiteCode(sysUser.getCompanyId());
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

    /**
     * 导入模板
     */
    @Override
    public String importTemplate() {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "发货单导入模板.xlsx";
        try {
            new ExcelExport(null, TbWmsMaterialDeliveryVo.class).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("生成发货单导入模板失败", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }

    /**
     * 导入
     * @param file
     * @param isUpdateSupport
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String importData(MultipartFile file, boolean isUpdateSupport) {
        List<TbWmsMaterialDeliveryVo> dataList = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int successNum = 0;
        int failureNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(TbWmsMaterialDeliveryVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }
        for (TbWmsMaterialDeliveryVo data : dataList) {
            try {
                TbWmsMaterialDeliverySaveParam saveParam = new TbWmsMaterialDeliverySaveParam();
                BeanUtils.copyProperties(data, saveParam);
                // 验证数据是否存在
                TbWmsMaterialDeliveryVo dataFromDb = this.findByOrderNo(data.getOrderNo());
                if (StringUtils.isNull(dataFromDb)) {
                    String id = this.insert(saveParam);
                    this.insertItem(saveParam,id);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、发货单 " + data.getOrderNo() + " 导入成功");
                } else if (isUpdateSupport) {
                    saveParam.setId(dataFromDb.getId());
                    this.insertItem(saveParam,dataFromDb.getId());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、发货单 " + data.getOrderNo() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、发货单 " + data.getOrderNo() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、发货单 " + data.getOrderNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ExcelException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Transactional(readOnly = false)
    @Override
    public CustomerConsignee generateConsigneeId(TbWmsMaterialDeliverySaveParam params,String userId,String customerNo) {
        CustomerConsignee customerConsignee = new CustomerConsignee();
        if(!StringUtils.isNull(params.getConsignee())){
            customerConsignee.setId(params.getConsignee());
        }else{
            customerConsignee.setId(idWorker.nextId() + "").preInsert(userId);
        }
        customerConsignee.setCustomerNo(customerNo);
        customerConsignee.setAreaDesc(params.getDestination());
        customerConsignee.setConsigneeAddress(params.getConsigneeAddress());
        customerConsignee.setLinkManMobile(params.getConsigneePhoneNo());
        customerConsignee.setConsigneeType(params.getCustomerType());

        customerConsignee.setConsigneeName(params.getConsigneeName());
        customerConsignee.setId(idWorker.nextId() + "").preInsert(userId);
        this.customerConsigneeMapper.insert(customerConsignee);
        return customerConsignee;
    }
    @Transactional(readOnly = false)
    @Override
    public String generateCustomer(TbWmsMaterialDeliverySaveParam params,String userId) {
        Customer entity = new Customer();
        String CustomerCode = tBmsAllGeneralSeqTabService.generateNo("CustomerCode");
        entity.setId(idWorker.nextId() + "")
                .preInsert(userId);
        entity.setCustomerCode("C".concat(CustomerCode));
        entity.setCity(params.getConsigneeCity());
        entity.setCustomerType(params.getCustomerType());
        entity.setAddress(params.getConsigneeAddress());
        entity.setCompanyName(params.getCustomerName());
        entity.setContactName(params.getShipperContact());
        entity.setContactPhone(params.getShipperPhoneNo());
        entity.setCustomerName(params.getCustomerName());
        entity.setLocationCode(params.getDeparture());
        this.customerMapper.insert(entity);
        return entity.getId();
    }




    @Transactional(readOnly = false)
    @Override
    public List<TbWmsMaterialDeliveryLine> insertALLToolsItem(TbWmsMaterialDeliverySaveParam params){
        // 收货人编码为空时，新增收货人
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
      /*  if(StringUtils.isNull(params.getCustomerNo())) {
            String customerNo = this.generateCustomer(params,sysUser.getId());
            params.setCustomerNo(customerNo);
        }*/
     /*  CustomerConsignee customerConsignee = null;
        if(!StringUtils.isNull(params.getConsignee())) {
             customerConsignee = this.customerConsigneeMapper.selectById(params.getConsignee());
            if(customerConsignee==null){
                customerConsignee = this.generateConsigneeId(params,sysUser.getId(),params.getCustomerNo());
                params.setConsignee(customerConsignee.getId());
            }

        }else {

            customerConsignee= this.generateConsigneeId(params,sysUser.getId(),params.getCustomerNo());
            params.setConsignee(customerConsignee.getId());
        }*/

        // 新增运单主表信息
        if(StringUtils.isNull(params.getOrderNo())){
            String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialDelivery");
            params.setOrderNo("R".concat(orderNo));
        }

        params.setSiteCode(sysUser.getOrgId())
                .setStatus(WmsInStatusEnum.created.getValue());


        String templateId = params.getId();

        String receiptId = this.insert(params);
        // 新增运单明细信息
        List<TbWmsMaterialDeliveryLine>  rt= this.insertToolsItem(params,receiptId,sysUser,templateId);

        return rt;
    }
    @Transactional(readOnly = false)
    @Override
    public String insertALLItem(TbWmsMaterialDeliverySaveParam params){
        // 收货人编码为空时，新增收货人
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String warehouseId = "";
        CustomerConsignee customerConsignee = null;
       if(StringUtils.isNull(params.getCustomerNo())) {
            String customerNo = this.generateCustomer(params,sysUser.getId());
            params.setCustomerNo(customerNo);
        }
        if(!StringUtils.isNull(params.getConsignee())) {
             customerConsignee = this.customerConsigneeMapper.selectById(params.getConsignee());
            if(customerConsignee==null){
                customerConsignee= this.generateConsigneeId(params,sysUser.getId(),params.getCustomerNo());
                params.setConsignee(customerConsignee.getId());
                params.setConsigneeName(customerConsignee.getConsigneeName());
            }
            params.setConsigneeName(customerConsignee.getConsigneeName());
            //查询收货人地址是否存在（如果不存在就新建一个地址跟仓库）
            CustomerConsigneeDeliveryAddress ccda= this.customerConsigneeDeliveryAddressMapper.findByCustCodeAndAddress(params.getReceitems().get(0).getConsigneeAddress(),params.getConsignee());

            if(ccda==null){
                 warehouseId = this.generateConsigneeWarehouse(params,sysUser.getId(),customerConsignee);
                ccda= this.generateConsigneeDeliveryAddress(params,sysUser.getId(),params.getConsignee(),warehouseId);
            }else{
                warehouseId = ccda.getWarehouseCode();
            }
        }else {

            customerConsignee = this.generateConsigneeId(params,sysUser.getId(),params.getCustomerNo());
            params.setConsignee(customerConsignee.getId());
            params.setConsigneeName(customerConsignee.getConsigneeName());
            //查询收货人地址是否存在（如果不存在就新建一个地址跟仓库）
            CustomerConsigneeDeliveryAddress ccda= this.customerConsigneeDeliveryAddressMapper.findByCustCodeAndAddress(params.getReceitems().get(0).getConsigneeAddress(),customerConsignee.getId());

            if(ccda==null){
                 warehouseId = this.generateConsigneeWarehouse(params,sysUser.getId(),customerConsignee);
                ccda=  this.generateConsigneeDeliveryAddress(params,sysUser.getId(),customerConsignee.getId(),warehouseId);
            }else{
                warehouseId =ccda.getWarehouseCode();
            }

        }

        // 新增运单主表信息
        if(StringUtils.isNull(params.getOrderNo())){
            String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialDelivery");
            params.setOrderNo("R".concat(orderNo));
        }

        params.setSiteCode(sysUser.getOrgId()).setDeliveryWarehouseCode(warehouseId).setDeliveryWarehouseName(params.getConsigneeName().concat("卸货库"))
                .setStatus(WmsInStatusEnum.created.getValue());




        String receiptId = this.insert(params);
        // 新增运单明细信息
        String rt= insertItem(params,receiptId);

        return rt;
    }

    //生成仓库
    private String generateConsigneeWarehouse(TbWmsMaterialDeliverySaveParam params, String userId, CustomerConsignee customerConsignee) {
        Warehouse warehouse = new Warehouse();

        warehouse.setId(idWorker.nextId() + "").preInsert(userId);
        warehouse.setOrgId(customerConsignee.getId());
        warehouse.setWarehouserCode("cosi".concat(warehouse.getId()));
        warehouse.setWarehouserName(customerConsignee.getConsigneeName().concat("卸货库"));
        warehouse.setWarehouseType("consignee");

        if(params.getReceitems().get(0).getDestination()!=null){
            String [] str = params.getReceitems().get(0).getDestination().split(",");
            warehouse.setProvince(str[0]);
            warehouse.setCity(str[1]);
            warehouse.setDistrict(str[2]);
        }
        warehouse.setAddress(params.getReceitems().get(0).getConsigneeAddress());
        this.warehouseMapper.insert(warehouse);
        return warehouse.getId();
    }

    //生成地址
    private CustomerConsigneeDeliveryAddress generateConsigneeDeliveryAddress(TbWmsMaterialDeliverySaveParam params, String userId, String consigneeId, String warehouseId) {
        CustomerConsigneeDeliveryAddress consigneeDeliveryAddress = new CustomerConsigneeDeliveryAddress();
        consigneeDeliveryAddress.setId(idWorker.nextId() + "").preInsert(userId);
        consigneeDeliveryAddress.setCcustcode(consigneeId);
        consigneeDeliveryAddress.setAeraDesc(params.getReceitems().get(0).getDestination());
        consigneeDeliveryAddress.setDeliveryAddress(params.getReceitems().get(0).getConsigneeAddress());
        consigneeDeliveryAddress.setWarehouseCode(warehouseId);
        consigneeDeliveryAddress.setSeq(Long.parseLong("0"));
        consigneeDeliveryAddress.setIsValid("1");
        this.customerConsigneeDeliveryAddressMapper.insert(consigneeDeliveryAddress);
        return consigneeDeliveryAddress;
    }



    @Transactional(readOnly = false)
    @Override
    public List<TbWmsMaterialDeliveryLine> insertToolsItem(TbWmsMaterialDeliverySaveParam deliverySaveParam,String deliveryId,UserVo user,String templateId) {
        List<TbWmsMaterialDeliveryLine> lines = new ArrayList<TbWmsMaterialDeliveryLine>();
        for(int i=0;i<deliverySaveParam.getIds().size();i++){
            TbWmsMaterialDeliveryLine line = this.tbWmsMaterialDeliveryLineMapper.selectById(deliverySaveParam.getIds().get(i));
            //List<TbWmsTemplateVo> tbWmsTemplates = this.tbWmsTemplateMapper.findByMaterialNo(line.getMaterialNo());
            TbWmsTemplateVo tbWmsTemplate = this.tbWmsTemplateMapper.findById(templateId);
            /*if(tbWmsTemplates ==null|| tbWmsTemplates.size()==0){
                throw new BusinessException("随车出库需要登记出库模版");
            }
            TbWmsTemplateVo tbWmsTemplate = tbWmsTemplates.get(0);*/
            if(tbWmsTemplate ==null){
                throw new BusinessException("随车出库需要登记出库模版");
            }
            List<TbWmsTemplateLine> templatelines = this.tbWmsTemplateLineMapper.findByTemplateId(tbWmsTemplate.getId());
            for (int j=0;j<templatelines.size();j++) {
                TbWmsTemplateLine tbWmsTemplateLine = templatelines.get(j);

                TbWmsMaterialDeliveryLine saveParam = new TbWmsMaterialDeliveryLine();
                BeanUtils.copyProperties(line,saveParam);
                saveParam.setDeparture(deliverySaveParam.getDeparture())
                        .setDeliveryId(deliveryId)
                        .setDestination(deliverySaveParam.getDestination())
                        .setOrderNo(deliverySaveParam.getOrderNo())
                        .setDeliveryWarehouseCode(line.getPickUpWarehouseNo())
                        .setPickUpWarehouseNo(deliverySaveParam.getWarehouseCode())
                        .setDeliveryType("tool")
                        .setUnloadDockCode(deliverySaveParam.getConsignee())
                        .setUnloadDockName(deliverySaveParam.getConsigneeName())
                        .setSite(deliverySaveParam.getSiteCode())
                        .setMaterialName(tbWmsTemplateLine.getMaterialName())
                        .setStatus(deliverySaveParam.getStatus())
                        .setMaterialNo(tbWmsTemplateLine.getMaterialNo()).setQuantity(tbWmsTemplateLine.getQuantity())
                        .setRemark(deliverySaveParam.getLineRemark());

                saveParam.setId(idWorker.nextId() + "").preInsert(user.getId());
                this.tbWmsMaterialDeliveryLineMapper.insert(saveParam);
                lines.add(saveParam);
                List<TbWmsMaterialInLocation> tbWmsMaterialInLocations = this.tbWmsMaterialInLocationMapper.findByMaterialNo(saveParam.getMaterialNo());
                double remainQty = saveParam.getQuantity();

                for(int k=0;k< tbWmsMaterialInLocations.size();k++){
                    TbWmsMaterialInLocation tbWmsMaterialInLocation = (TbWmsMaterialInLocation)tbWmsMaterialInLocations.get(k);
                    if(tbWmsMaterialInLocation.getQuantity()>remainQty){
                        double nowqty =NumberUtils.sub(tbWmsMaterialInLocation.getQuantity(),remainQty);
                        tbWmsMaterialInLocation.setQuantity(nowqty);
                        tbWmsMaterialInLocation.preUpdate(user.getId());
                        this.tbWmsMaterialInLocationMapper.updateById(tbWmsMaterialInLocation);
                        break;
                    }else if(tbWmsMaterialInLocation.getQuantity()==remainQty){

                        this.tbWmsMaterialInLocationMapper.deleteById(tbWmsMaterialInLocation.getId());
                        break;
                    }else {
                        remainQty = NumberUtils.sub(remainQty,tbWmsMaterialInLocation.getQuantity());
                        this.tbWmsMaterialInLocationMapper.deleteById(tbWmsMaterialInLocation.getId());
                    }
                }

            }
        }

     //
      //  TbWmsTemplate tbWmsTemplate = this.tbWmsTemplateMapper.selectById(deliverySaveParam.getTemplateId());


        return lines;
    }
    public String insertItem( TbWmsMaterialDeliverySaveParam deliverySaveParam,String deliveryId) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        for (TbWmsMaterialDeliveryLineSaveParam saveParam : deliverySaveParam.getReceitems()) {
            String rid = saveParam.getReceivedLineId();
            TbWmsMaterialReceiptLine line  = this.tbWmsMaterialReceiptLineMapper.selectById(rid);
            List<TbWmsMaterialInLocation> tbWmsMaterialInLocationList = this.tbWmsMaterialInLocationMapper.findByReciptLineId(rid);

            TbWmsMaterialReceipt receipt = null;
            if(line!=null){
                receipt = this.tbWmsMaterialReceiptMapper.selectById(line.getReceiptId());
                BeanUtils.copyProperties(line,saveParam);
            }


            saveParam.setDeparture(deliverySaveParam.getDeparture())
                    .setDeliveryId(deliveryId)
                    .setMaterialName(line.getMaterialName())
                    .setMaterialVehicleInLocationId(saveParam.getLocationNo())
                    .setMaterialNo(line.getMaterialNo())
                    .setPickUpWarehouseNo(deliverySaveParam.getWarehouseCode())
                    .setDeliveryWarehouseCode(deliverySaveParam.getDeliveryWarehouseCode())
                    .setDeliveryWarehouseName(deliverySaveParam.getDeliveryWarehouseName())
                    .setDestination(deliverySaveParam.getDestination())
                    .setOrderNo(deliverySaveParam.getOrderNo())
                    .setUnloadDockCode(deliverySaveParam.getConsignee())
                    .setUnloadDockName(deliverySaveParam.getConsigneeName())
                    .setSite(deliverySaveParam.getSiteCode())
                    .setStatus(deliverySaveParam.getStatus())
                    .setRemark(deliverySaveParam.getLineRemark());

             if(tbWmsMaterialInLocationList.size()>0){
                 saveParam.setMaterialVehicleInLocationId(tbWmsMaterialInLocationList.get(0).getId());
             }
             materialDeliveryLineService.insert(saveParam);

            if(receipt!=null){
                receipt.setStatus(WmsInStatusEnum.outPlaned.getValue());
                receipt.preUpdate(sysUser.getId());
                this.tbWmsMaterialReceiptMapper.updateById(receipt);
            }

            line.setStatus(WmsInStatusEnum.outPlaned.getValue());
            line.preUpdate(sysUser.getId());
            this.tbWmsMaterialReceiptLineMapper.updateById(line);


        }
      //  TbWmsMaterialDelivery order = BeanUtils.copyProperties(deliverySaveParam,order);
      //  this.findByDateAndShipperAndUpdateCalendar(order,order.getCustomerNo(),sysUser);
        return "success";
    }
    public void findByDateAndShipperAndUpdateCalendar(TbWmsMaterialDelivery order,String custNo,UserVo user){

        String datestr = DateUtils.parseDateToStr("yyyyMMdd",order.getCreateDate());
        String year = datestr.substring(0,4);
        String month = datestr.substring(4,6);
        if(month.startsWith("0"))
        {
            month = month.substring(1);
        }
        String day=datestr.substring(6,8);
        List<MyCalendar> calendars = this.myCalendarMapper.findCalendarByShipper(year,month,custNo);
        if(calendars==null||calendars.size()==0){
            return;
        }


        MyCalendar mycalendar = (MyCalendar)calendars.get(0);
        String flag = "N";
        int wkday = 0;
        if(StringUtils.isNull(mycalendar.getSundaydate())&&(Double.valueOf(mycalendar.getFirstdayat()).doubleValue()+Double.valueOf(day).doubleValue())<=7){

            wkday = this.findWeekDayByWeekAndYear(mycalendar, day);
            switch(wkday){
                case 0:{
                    String preNo = mycalendar.getSun();
                    if(StringUtils.isNull(preNo)){
                        mycalendar.setSun("1");
                    }else{
                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                        mycalendar.setSun(String.valueOf(num));
                    }
                    break;
                }
                case 1:{
                    String preNo = mycalendar.getMon();
                    if(StringUtils.isNull(preNo)){
                        mycalendar.setMon("1");
                    }else{
                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                        mycalendar.setMon(String.valueOf(num));
                    }
                    break;
                }
                case 2:{
                    String preNo = mycalendar.getTue();
                    if(StringUtils.isNull(preNo)){
                        mycalendar.setTue("1");
                    }else{
                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                        mycalendar.setTue(String.valueOf(num));
                    }
                    break;
                }
                case 3:{
                    String preNo = mycalendar.getWed();
                    if(StringUtils.isNull(preNo)){
                        mycalendar.setWed("1");
                    }else{
                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                        mycalendar.setWed(String.valueOf(num));
                    }
                    break;
                }
                case 4:{
                    String preNo = mycalendar.getThu();
                    if(StringUtils.isNull(preNo)){
                        mycalendar.setThu("1");
                    }else{
                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                        mycalendar.setThu(String.valueOf(num));
                    }
                    break;
                }
                case 5:{
                    String preNo = mycalendar.getFri();
                    if(StringUtils.isNull(preNo)){
                        mycalendar.setFri("1");
                    }else{
                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                        mycalendar.setFri(String.valueOf(num));
                    }
                    break;
                }
                case 6:{
                    String preNo = mycalendar.getSat();
                    if(StringUtils.isNull(preNo)){
                        mycalendar.setSat("1");
                    }else{
                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                        mycalendar.setSat(String.valueOf(num));
                    }
                    break;
                }
            }

            mycalendar.preUpdate(user.getId());
             this.myCalendarMapper.updateById(mycalendar);

        }else{
            for(int i=1;i<calendars.size();i++){
                MyCalendar nextcalendar = (MyCalendar)calendars.get(i);

                if(!StringUtils.isNull(nextcalendar.getSundaydate())){
                    if(Double.valueOf(day).doubleValue()>=Double.valueOf(nextcalendar.getSundaydate())){
                        if(Double.valueOf(day).doubleValue()-Double.valueOf(nextcalendar.getSundaydate())<7){
                            wkday = this.findWeekDayByWeekAndYear(nextcalendar, day);
                            switch(wkday){
                                case 0: {
                                    String preNo = nextcalendar.getSun();
                                    if(StringUtils.isNull(preNo)){
                                        nextcalendar.setSun("1");
                                    }else{
                                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                                        nextcalendar.setSun(String.valueOf(num));
                                    }
                                    break;
                                }
                                case 1: {
                                    String preNo = nextcalendar.getMon();
                                    if(StringUtils.isNull(preNo)){
                                        nextcalendar.setMon("1");
                                    }else{
                                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                                        nextcalendar.setMon(String.valueOf(num));
                                    }
                                    break;
                                }
                                case 2:{
                                    String preNo = nextcalendar.getTue();
                                    if(StringUtils.isNull(preNo)){
                                        nextcalendar.setTue("1");
                                    }else{
                                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                                        nextcalendar.setTue(String.valueOf(num));
                                    }
                                    break;
                                }
                                case 3:{
                                    String preNo = nextcalendar.getWed();
                                    if(StringUtils.isNull(preNo)){
                                        nextcalendar.setWed("1");
                                    }else{
                                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                                        nextcalendar.setWed(String.valueOf(num));
                                    }
                                    break;
                                }
                                case 4:{
                                    String preNo = nextcalendar.getThu();
                                    if(StringUtils.isNull(preNo)){
                                        nextcalendar.setThu("1");
                                    }else{
                                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                                        nextcalendar.setThu(String.valueOf(num));
                                    }
                                    break;
                                }
                                case 5:{
                                    String preNo = nextcalendar.getFri();
                                    if(StringUtils.isNull(preNo)){
                                        nextcalendar.setFri("1");
                                    }else{
                                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                                        nextcalendar.setFri(String.valueOf(num));
                                    }
                                    break;
                                }
                                case 6:{
                                    String preNo = nextcalendar.getSat();
                                    if(StringUtils.isNull(preNo)){
                                        nextcalendar.setSat("1");
                                    }else{
                                        double num = NumberUtils.add(Double.valueOf(preNo),1);
                                        nextcalendar.setSat(String.valueOf(num));

                                    }
                                    break;
                                }
                            }//end switch

                            nextcalendar.preUpdate(user.getId());
                            this.myCalendarMapper.updateById(nextcalendar);
                        }//end <7
                    }//end day > sunday
                    else{
                        flag = "Y";
                        break;
                    }
                }//sunday not null
                else{
                    wkday = this.findWeekDayByWeekAndYear(mycalendar, day);
                    switch(wkday){
                        case 0:{
                            String preNo = mycalendar.getSun();
                            if(StringUtils.isNull(preNo)){
                                mycalendar.setSun("1");
                            }else{
                                double num = NumberUtils.add(Double.valueOf(preNo),1);
                                mycalendar.setSun(String.valueOf(num));
                            }
                            break;
                        }
                        case 1:{
                            String preNo = mycalendar.getMon();
                            if(StringUtils.isNull(preNo)){
                                mycalendar.setMon("1");
                            }else{
                                double num = NumberUtils.add(Double.valueOf(preNo),1);
                                mycalendar.setMon(String.valueOf(num));
                            }
                            break;
                        }
                        case 2:{
                            String preNo = mycalendar.getTue();
                            if(StringUtils.isNull(preNo)){
                                mycalendar.setTue("1");
                            }else{
                                double num = NumberUtils.add(Double.valueOf(preNo),1);
                                mycalendar.setTue(String.valueOf(num));
                            }
                            break;
                        }
                        case 3:{
                            String preNo = mycalendar.getWed();
                            if(StringUtils.isNull(preNo)){
                                mycalendar.setWed("1");
                            }else{
                                double num = NumberUtils.add(Double.valueOf(preNo),1);
                                mycalendar.setWed(String.valueOf(num));
                            }
                            break;
                        }
                        case 4:{
                            String preNo = mycalendar.getThu();
                            if(StringUtils.isNull(preNo)){
                                mycalendar.setThu("1");
                            }else{
                                double num = NumberUtils.add(Double.valueOf(preNo),1);
                                mycalendar.setThu(String.valueOf(num));
                            }
                            break;
                        }
                        case 5:{
                            String preNo = mycalendar.getFri();
                            if(StringUtils.isNull(preNo)){
                                mycalendar.setFri("1");
                            }else{
                                double num = NumberUtils.add(Double.valueOf(preNo),1);
                                mycalendar.setFri(String.valueOf(num));
                            }
                            break;
                        }
                        case 6:{
                            String preNo = mycalendar.getSat();
                            if(StringUtils.isNull(preNo)){
                                mycalendar.setSat("1");
                            }else{
                                double num = NumberUtils.add(Double.valueOf(preNo),1);
                                mycalendar.setSat(String.valueOf(num));
                            }
                            break;
                        }
                    }

                    mycalendar.preUpdate(user.getId());
                    this.myCalendarMapper.updateById(mycalendar);
                }

            }
        }

    }
    public int findWeekDayByWeekAndYear(MyCalendar mycalendar,String date){
        int weekday=0;
        if(mycalendar.getZhou().equals("1")){
            weekday = Long.valueOf(date).intValue()+Long.valueOf(mycalendar.getFirstdayat()).intValue()-1;
        }else{
            weekday = Long.valueOf(date).intValue()-Long.valueOf(mycalendar.getSundaydate()).intValue();

        }
        return weekday;
    }
}
